<?php

require_once "../includes/db_lib.php";
require_once "../includes/media.php";

function make_thumbnail($photo_filename, $now) {
	$scale = 0.2;

	$full_img = imagecreatefromjpeg($photo_filename);
  	$full_x = imagesx($full_img);
  	$full_y = imagesy($full_img);
  	$thumb_x = $scale * $full_x;
  	$thumb_y = $scale * $full_y;
  	$thumb_img = imagecreatetruecolor($thumb_x, $thumb_y);
  	imagecopyresampled($thumb_img, $full_img, 0, 0, 0, 0, $thumb_x, $thumb_y, $full_x, $full_y);
  	$thumb_filename = "thumb/$now.jpg";
  	imagejpeg($thumb_img, $thumb_filename, 100);
}

function run() {
	try {
		$m = new Media($_POST);
		
		$now = time();
		
		$photo_filename = "photo/$now.jpg";
		$m->photo_filename_is($photo_filename);
		
		if ($_FILES["audio_file"] != null) {
			$audio_filename = "audio/$now.mp4";
			$m->audio_filename_is($audio_filename);
		}
		
		$m->save();
		
		// If save went through, then we can copy the content over if necessary.
    	move_uploaded_file($_FILES["photo_file"]["tmp_name"], $m->photo_filename());
  		if ($audio_filename != null) {
  			move_uploaded_file($_FILES["audio_file"]["tmp_name"], $m->audio_filename());
  		}
  		
  		// make thumbnail image
  		make_thumbnail($photo_filename, $now);
		
	} catch (Exception $e) {
		echo header("HTTP/1.1 500 Internal Server Error");
		echo $e;
	}
}

run();

?>
